import './style.css';
import { initCharts, updateChart, updateMetricValue, resizeCharts, metricsConfig } from './chart.js';
import { WebSocketManager } from './websocket.js';

// WebSocket配置
const WS_URL = 'ws://localhost:8080';

// 初始化图表
const charts = initCharts();

// 创建WebSocket管理器
const wsManager = new WebSocketManager(WS_URL, {
    reconnectDelay: 5000,
    maxReconnectAttempts: Infinity
});
//timestamp
// 处理WebSocket消息
wsManager.onMessage((message) => {
    if (message.type === 'update' && message.data) {
       const data = message.data;
       let ts = message.timestamp
        
        // 更新所有指标
        Object.keys(metricsConfig).forEach(key => {
            const value = data[metricsConfig[key].key];
            if (value !== undefined) {
                updateChart(charts, key, value, ts);
                updateMetricValue(key, value);
            }
        });
    }
});

// 处理连接状态变化
wsManager.onStatusChange((isConnected) => {
    const statusEl = document.getElementById('connectionStatus');
    if (statusEl) {
        if (isConnected) {
            statusEl.textContent = '● 已连接';
            statusEl.className = 'connection-status connected';
        } else {
            statusEl.textContent = '● 连接断开';
            statusEl.className = 'connection-status disconnected';
        }
    }
});

// 窗口大小改变时重新调整图表
let resizeTimer;
window.addEventListener('resize', () => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(() => {
        resizeCharts(charts);
    }, 200);
});

// 页面加载完成后连接WebSocket
window.addEventListener('load', () => {
    wsManager.connect();
});

// 页面关闭时清理
window.addEventListener('beforeunload', () => {
    wsManager.close();
});

// 导出给调试使用
if (import.meta.env.DEV) {
    window.__charts__ = charts;
    window.__wsManager__ = wsManager;
}